package com.douyin.controller;

import com.douyin.dto.FindPasswordDTO;
import com.douyin.dto.LoginDTO;
import com.douyin.dto.RegisterDTO;
import com.douyin.entity.Captcha;
import com.douyin.service.LoginService;
import com.douyin.utils.R;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/douyin/login")
@Slf4j
public class LoginController {
    @Autowired
    private LoginService loginService;
    @GetMapping("/captcha.jpg/{uuId}")
    public void getCaptcha(HttpServletResponse response, @PathVariable String uuId) throws IOException {
        log.info("获取图形验证码, uuId: {}", uuId);
        loginService.getCaptcha(response, uuId);
    }

    @PostMapping("/getCode")
    public R getCode(@RequestBody Captcha captcha){
        log.info("获取邮箱验证码, uuId: {}, code: {}, email: {}", captcha.getUuid(), captcha.getCode(),captcha.getEmail());
        if (!loginService.getCode(captcha)){
            return R.error().message("图形验证码错误");
        }
        return R.ok().message("邮箱验证码发送成功");
    }

    @PostMapping("/check")
    public R check(String email, Integer code){
        log.info("校验邮箱验证码, email: {}, code: {}", email, code);
        loginService.checkCode(email, code);
        return R.ok().message("邮箱验证码校验成功");
    }

    @PostMapping("/register")
    public R register(@RequestBody RegisterDTO registerDTO){
        log.info("注册, registerDTO: {}", registerDTO);
        loginService.register(registerDTO);
        return R.ok().message("注册成功");
    }

    @PostMapping
    public R login(@RequestBody LoginDTO loginDTO){
        log.info("登录, loginDTO: {}", loginDTO);
        Map<String, Object> result = loginService.login(loginDTO);
        return R.ok().data(result);
    }


    @PostMapping("/findPassword")
    public R findPassword(@RequestBody FindPasswordDTO findPasswordDTO){
        log.info("找回密码, findPasswordDTO: {}", findPasswordDTO);
        loginService.findPassword(findPasswordDTO);
        return R.ok().message("新密码设置成功");
    }

}
